package com.bt.mes.common.core.rabbitmq;

import java.util.ArrayList;
import java.util.List;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

@Component
public class RabbitmqManager {
	RabbitTemplate rabbitTemplate;
	AmqpAdmin admin;

	public void setAdmin(AmqpAdmin admin) {
		this.admin = admin;
	}

	public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
		this.rabbitTemplate = rabbitTemplate;
	}

	public void setMessage(String queuename, String message) {
		Queue queue = new Queue(queuename, true);
		this.admin.declareQueue(queue);

		this.rabbitTemplate.convertAndSend(queuename, message);
	}

	public String recieveMessage(String queuename) {
		try {
			Queue queue = new Queue(queuename, true);
			this.admin.declareQueue(queue);

			return (String) this.rabbitTemplate.receiveAndConvert(queuename);
		} catch (AmqpException e) {
			System.out.println("cannot get message " + e.getMessage());
		}
		return null;
	}

	public List<String> recieveAllMessage(String queuename) {
		try {
			List<String> list = new ArrayList<String>();
			String message = recieveMessage(queuename);
			while (message != null) {
				list.add(message);

				TopicExchange exchange = new TopicExchange("Exchang_" + queuename, true, false);
				Queue queue = new Queue(queuename, true);
				this.admin.declareQueue(queue);
				this.admin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(queuename));
				message = (String) this.rabbitTemplate.receiveAndConvert(queuename);
			}
			return list;
		} catch (AmqpException e) {
			System.out.println("cannot get message " + e.getMessage());
		}
		return null;
	}
}
